package com.supply.dl.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.supply.dl.R;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalAdapter;
import com.supply.dl.app.adapter.NormalPositionAdapter;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.BaseObserver;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.JobAttachBean;
import com.supply.dl.bean.JobInfoBean;
import com.supply.dl.bean.MaterierSendGoodPost;
import com.supply.dl.bean.MeasureUnit;
import com.supply.dl.bean.PickSendGoodsDetail;
import com.supply.dl.bean.PositionInfoBean;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.WorkInfoBean;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.utils.BigDecimalUtil;
import com.supply.dl.utils.DealWithInputUtil;
import com.supply.dl.utils.FilePostUtil;
import com.supply.dl.utils.PictureHelper;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.view.MyGridView;
import com.supply.dl.widget.adapter.GridViewImageAdapter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 领料发货详情页,注意所有的
 * <p>
 * Author: tian <br>
 * Time: 2018/6/12 15:20
 */
public class PickDeliverGoodsActivity extends BaseActivity {

    /**
     * 通知单id,和通知单号
     */
    private String noticeOrderId, noticeOrderNo;

    /**
     * 物料列表
     */
    @BindView(R.id.materail_rc)
    MaxRecyclerView materail_rc;

    /**
     * 物料横向列表 适配器
     */
    private NormalAdapter<WorkInfoBean> materielAdapter;

    /**
     * 物料列表数据，已作业物料数据，未作业物料数据
     */
    private List<WorkInfoBean> itemList, hasDoList, unDoList;

    /**
     * 详情数据
     */
    private PickSendGoodsDetail mDetail;

    /**
     * 未作业
     */
    @BindView(R.id.un_location_tv)
    TextView notLocatedTv;

    @BindView(R.id.unlocation_line)
    View notLocatedLineView;

    /**
     * 已作业
     */
    @BindView(R.id.located_tv)
    TextView hadLocatedTv;

    @BindView(R.id.had_location_line)
    View hadLocatedLineView;

    /**
     * 添加作业按钮
     */
    @BindView(R.id.add_location_tv)
    TextView addNewWork;

    /**
     * 批量作业
     */
    @BindView(R.id.location_lot_tv)
    TextView batchPositionBtn;

    /**
     * 作业列表
     */
    @BindView(R.id.location_rc)
    MaxRecyclerView workRecylerView;

    /**
     * 通知单号
     */
    @BindView(R.id.common_letter_of_notice_info_showNoticeLetterNo)
    TextView showNoticeLetterNo;

    /**
     * 作业状态
     */
    @BindView(R.id.common_letter_of_notice_info_positionStatusName)
    TextView positionStatusName;

    /**
     * 业务类型
     */
    @BindView(R.id.common_letter_of_notice_info_showFirstValue)
    TextView showFirstValue;

    /**
     * 供应商信息
     */
    @BindView(R.id.common_letter_of_notice_info_showSecondValue)
    TextView showSecondValue;

    /**
     * 车牌号
     */
    @BindView(R.id.common_letter_of_notice_info_showThirdValue)
    TextView showThirdValue;

    /**
     * 司机名字
     */
    @BindView(R.id.common_letter_of_notice_info_showFourthValue)
    TextView showFourthValue;

    /**
     * 物料编码
     */
    @BindView(R.id.common_materiel_position_info_showFirstValue)
    TextView showMaterielFirstValue;

    /**
     * 物料名称
     */
    @BindView(R.id.common_materiel_position_info_showSecondValue)
    TextView showMaterielSecondValue;

    /**
     * 总数
     */
    @BindView(R.id.common_materiel_position_info_showThirdValue)
    TextView showMaterielThirdValue;

    /**
     * 标记是未作业还是已作业
     */
    @BindView(R.id.common_materiel_position_info_fourthTv)
    TextView materielFourthTv;

    /**
     * 未作业数量、已作业数量
     */
    @BindView(R.id.common_materiel_position_info_showFourthValue)
    TextView showMaterielFourthValue;

    /**
     * 作业列表数据
     */
    private ArrayList<MeasureUnit> workDatas;

    /**
     * 作业列表适配器
     */
    private NormalPositionAdapter<MeasureUnit> workAdapter;

    /**
     * 标记当前 是否是显示的 未作业信息
     */
    private boolean hasPositionShow;

    /**
     * 当前被选中的 物料对象
     */
    private WorkInfoBean currentShowMaterier;


    /**
     * 当前作业或者未作业 item项
     */
    private Object currentPostionItem;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_normal_detail_main;
    }

    @Override
    protected void initView() {
        super.initView();
        showLeftBack();
        setTitleShow("领料发货详情");
        addNewWork.setText("添加作业");

        setRightHomeClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(PickDeliverGoodsActivity.this, "home");
            }
        });

        setRightScanClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(PickDeliverGoodsActivity.this, "scan");
                Utils.startScanActivity(PickDeliverGoodsActivity.this);
            }
        });

        noticeOrderId = getIntent().getStringExtra("noticeOrderId");
        noticeOrderNo = getIntent().getStringExtra("noticeOrderNo");

        getMaterierSendGoodDetail();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        itemList = new ArrayList<>();
        hasDoList = new ArrayList<>();
        unDoList = new ArrayList<>();
        workDatas = new ArrayList<>();
    }

    @Override
    protected void initRecyclerView() {

        //初始化物料列表
        materielAdapter = new NormalAdapter<WorkInfoBean>(this, itemList) {
            @Override
            protected void convert(ViewHolder holder, WorkInfoBean data) {
                TextView name_tv = holder.getView(R.id.material_position_info_item_textView);
                if (data.isSelected) {
                    name_tv.setBackgroundResource(R.drawable.shape_search_btn_blue_bg);
                    name_tv.setTextColor(getResources().getColor(R.color.whiteColor));
                }
                //
                else {
                    name_tv.setBackgroundResource(R.drawable.shape_solid_gray_bg);
                    name_tv.setTextColor(getResources().getColor(R.color.textColor));
                }
                name_tv.setText(data.skuName);
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.materiel_position_info_item;
            }
        };
        //点击事件
        materielAdapter.setOnItemClickListener(new NormalAdapter.OnItemClickListener<WorkInfoBean>() {
            @Override
            public void onItemClick(ViewHolder viewHolder, WorkInfoBean data, int position) {

                for (WorkInfoBean item : itemList) {
                    if (!item.skuId.equals(data.skuId))
                        item.isSelected = false;
                    else
                        item.isSelected = true;
                }

                materielAdapter.notifyDataSetChanged();
                fillMaterialView();
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        materail_rc.setLayoutManager(linearLayoutManager);
        materail_rc.setAdapter(materielAdapter);
        //初始化
        workAdapter = new NormalPositionAdapter<MeasureUnit>(this, workDatas) {
            @Override
            protected void convert(ViewHolder holder, final MeasureUnit data, int index) {

                final TextView sure_location_tv = holder.getView(R.id.work_info_item_sureWorkBtn);

                holder.setText(R.id.work_info_item_workOrderNumberTextView, "作业" + (index + 1));
                holder.getView(R.id.danjian_weight_ly).setVisibility(View.GONE);

                TextView notesTv = holder.getView(R.id.work_info_item_showJobRecordTv);
                final EditText amount_et = holder.getView(R.id.work_info_item_showNumberForPieceTv);
                final EditText weight_et = holder.getView(R.id.work_info_item_showWeightForTonTv);
                final EditText volume_et = holder.getView(R.id.work_info_item_showVolumeForSquareTv);

                //展示未作业信息中的 推荐作业信息
                if (data instanceof PositionInfoBean) {

                    PositionInfoBean pb = (PositionInfoBean) data;
                    holder.setText(R.id.work_info_item_showReservoirPositionTv, pb.stockName);
                    holder.setText(R.id.work_info_item_showStorehouseTv, pb.whName);
                    amount_et.setText(pb.amount == null ? "" : (pb.amount + ""));
                    weight_et.setText(pb.weight == null ? "" : (pb.weight + ""));
                    volume_et.setText(pb.volume == null ? "" : (pb.volume + ""));
                    holder.setText(R.id.work_info_item_showInventoryStatusTv, pb.stockStatusName);
                    holder.setText(R.id.work_info_item_showInventoryTypeTv, pb.stockTypeName);
                    holder.setText(R.id.work_info_item_showStandardTv, pb.unitName);
                    holder.setText(R.id.work_info_item_showBatchNumberTv, pb.batchNo);
                    holder.setText(R.id.work_info_item_showRemarksTv, StringUtils.isCanUse(pb.remark) ? pb.remark : "");

                    if (pb.isPostPositon) {
                        sure_location_tv.setText("已提交作业信息");
                    }
                    //
                    else {
                        sure_location_tv.setText("保存作业");
                    }

                    if (pb.getJobAmountList() != null && pb.getJobAmountList().size() > 0) {
                        notesTv.setText("已填写");
                    }
                    //
                    else {
                        notesTv.setText("未填写");
                    }

                }
                //展示已作业信息中的 已作业信息
                else {
                    JobInfoBean jb = (JobInfoBean) data;
                    holder.setText(R.id.work_info_item_showReservoirPositionTv, jb.actualStockName);
                    holder.setText(R.id.work_info_item_showStorehouseTv, jb.actualWhName);
                    amount_et.setText(jb.actualAmount == null ? "" : (jb.actualAmount + ""));
                    weight_et.setText(jb.actualWeight == null ? "" : (jb.actualWeight + ""));
                    volume_et.setText(jb.actualVolume == null ? "" : (jb.actualVolume + ""));
                    holder.setText(R.id.work_info_item_showInventoryStatusTv, jb.stockStatusName);
                    holder.setText(R.id.work_info_item_showInventoryTypeTv, jb.stockTypeName);
                    holder.setText(R.id.work_info_item_showStandardTv, jb.unitName);
                    holder.setText(R.id.work_info_item_showBatchNumberTv, jb.batchNo);
                    holder.setText(R.id.work_info_item_showRemarksTv, StringUtils.isCanUse(jb.remark) ? jb.remark : "");

                    if (jb.isPostPositon) {
                        sure_location_tv.setText("已提交作业信息");
                    }
                    //
                    else {
                        sure_location_tv.setText("保存作业");
                    }

                    if (jb.getJobAmountList() != null && jb.getJobAmountList().size() > 0) {
                        notesTv.setText("已填写");
                    }
                    //
                    else {
                        notesTv.setText("未填写");
                    }
                }

                amount_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (!StringUtils.isCanUse(s.toString()))
                            return;
                        new DealWithInputUtil(PickDeliverGoodsActivity.this, currentShowMaterier, data, workDatas)
                                .dealMaterierSendOperateInput(BigDecimalUtil.getBigDecimalByString(s.toString()), amount_et);
                    }
                });
                weight_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                        if (!StringUtils.isCanUse(s.toString()))
                            return;
                        new DealWithInputUtil(PickDeliverGoodsActivity.this, currentShowMaterier, data, workDatas)
                                .dealMaterierSendOperateInput(BigDecimalUtil.getBigDecimalByString(s.toString()), weight_et);
                    }
                });
                volume_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (!StringUtils.isCanUse(s.toString()))
                            return;
                        new DealWithInputUtil(PickDeliverGoodsActivity.this, currentShowMaterier, data, workDatas)
                                .dealMaterierSendOperateInput(BigDecimalUtil.getBigDecimalByString(s.toString()), volume_et);
                    }
                });

                ((EditText) holder.getView(R.id.work_info_item_showRemarksTv)).addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                        if (!StringUtils.isCanUse(s.toString()))
                            return;

                        if (data instanceof PositionInfoBean) {
                            PositionInfoBean rib = (PositionInfoBean) data;
                            rib.remark = s.toString();
                        }
                        //
                        else {
                            JobInfoBean pib = (JobInfoBean) data;
                            pib.remark = s.toString();
                        }
                    }
                });

                holder.getView(R.id.work_info_item_showReservoirPositionTv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("已提交作业信息".equals(sure_location_tv.getText().toString())) {
                            return;
                        }

                        Bundle bundle = new Bundle();
                        //物料编码
                        bundle.putString("skuId", currentShowMaterier.skuCode);
                        //页面名字
                        bundle.putString("titleName", "库位选择");
                        //仓库id
                        bundle.putString("whId", "");

                        Intent it = new Intent(PickDeliverGoodsActivity.this, DepotSelectActivity.class);
                        it.putExtras(bundle);
                        startActivityForResult(it, AppConfig.BaseDataAction.REQCODE_CHOOSE_STOCK);

                        currentPostionItem = data;
                    }
                });

                holder.getView(R.id.work_info_item_workDeleteTv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(PickDeliverGoodsActivity.this, "暂不支持删除功能!", Toast.LENGTH_SHORT).show();
                    }
                });


                //作业记录的选择和填写
                notesTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        currentPostionItem = data;
                        Intent intent = new Intent(PickDeliverGoodsActivity.this, OperateRemarkActivity.class);
                        intent.putExtra("factoryId", "");
                        PickDeliverGoodsActivity.this.startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_ADD_OPERATE_REMARK);
                    }
                });

                sure_location_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        currentPostionItem = data;

                        ArrayList<JobAttachBean> files;
                        if (currentPostionItem instanceof PositionInfoBean) {
                            PositionInfoBean pf = (PositionInfoBean) currentPostionItem;
                            files = pf.getJobAttachList();
                        }
                        //
                        else {
                            JobInfoBean jb = (JobInfoBean) currentPostionItem;
                            files = jb.getJobAttachList();
                        }

                        if (files.size() > 0)

                            FilePostUtil.postFile(PickDeliverGoodsActivity.this, files, new FilePostUtil.OnFilePostEndListener() {
                                @Override
                                public void onFilePostEnd() {
                                    saveOperate();
                                }
                            });
                        else
                            saveOperate();
                    }
                });

                final ArrayList<JobAttachBean> jobAttachList = new ArrayList<>();

                if (data instanceof PositionInfoBean) {
                    PositionInfoBean pf = (PositionInfoBean) data;
                    jobAttachList.clear();
                    jobAttachList.addAll(pf.jobAttachList);
                }
                //
                else {
                    JobInfoBean jb = (JobInfoBean) data;

                    jobAttachList.clear();
                    jobAttachList.addAll(jb.jobAttachList);
                }

                MyGridView mGridView = holder.getView(R.id.work_info_item_gridView);
                GridViewImageAdapter mAdapter = new GridViewImageAdapter(mContext, holder.getLayoutPosition(),
                        new GridViewImageAdapter.OnAddOrDeletClickListener() {
                            @Override
                            public void onAddClick() {
                                currentPostionItem = data;
                                PictureHelper.toSelectPicture(PickDeliverGoodsActivity.this);
                            }

                            @Override
                            public void onDeleteClick(JobAttachBean jobAttachBean) {
                                currentPostionItem = data;

                                jobAttachList.remove(jobAttachBean);

                                if (data instanceof PositionInfoBean) {
                                    PositionInfoBean pf = (PositionInfoBean) data;
                                    pf.getJobAmountList().remove(jobAttachBean);
                                }
                                //
                                else {
                                    JobInfoBean jb = (JobInfoBean) data;
                                    jb.getJobAttachList().remove(jobAttachBean);
                                }
                            }
                        });
                mAdapter.setData(jobAttachList);
                mGridView.setAdapter(mAdapter);
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.work_info_item;
            }
        };
        workRecylerView.setLayoutManager(new LinearLayoutManager(this));
        workRecylerView.setAdapter(workAdapter);

        isHadLocation(false);
    }

    @OnClick({R.id.un_location_tv, R.id.located_tv, R.id.add_location_tv, R.id.location_lot_tv})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.un_location_tv://未作业
                isHadLocation(false);
                break;
            case R.id.located_tv://已作业
                isHadLocation(true);
                break;
            case R.id.add_location_tv://添加新作业

                if (currentShowMaterier == null) {
                    Toast.makeText(this, "没有物料不能进行添加新作业操作", Toast.LENGTH_SHORT).show();
                    return;
                }

                currentPostionItem = null;

                Bundle bundle = new Bundle();
                //物料编码
                bundle.putString("skuId", currentShowMaterier.skuCode);
                //页面名字
                bundle.putString("titleName", "库位选择");
                //仓库id
                bundle.putString("whId", "");

                Intent it = new Intent(PickDeliverGoodsActivity.this, DepotSelectActivity.class);
                it.putExtras(bundle);
                startActivityForResult(it, AppConfig.BaseDataAction.REQCODE_CHOOSE_STOCK);

                break;
        }
    }

    /**
     * 是否作业
     *
     * @param isLocation
     */
    private void isHadLocation(boolean isLocation) {

        hasPositionShow = isLocation;

        if (!isLocation) {
            notLocatedLineView.setVisibility(View.VISIBLE);
            hadLocatedLineView.setVisibility(View.INVISIBLE);
            batchPositionBtn.setVisibility(View.GONE);
            notLocatedTv.setTextColor(getResources().getColor(R.color.blue));
            hadLocatedTv.setTextColor(getResources().getColor(R.color.color_gray));

            //显示的数据进行切换
            itemList.clear();
            itemList.addAll(unDoList);
            materielAdapter.notifyDataSetChanged();
        }
        //
        else {
            hadLocatedLineView.setVisibility(View.VISIBLE);
            notLocatedLineView.setVisibility(View.INVISIBLE);
            batchPositionBtn.setVisibility(View.GONE);
            hadLocatedTv.setTextColor(getResources().getColor(R.color.blue));
            notLocatedTv.setTextColor(getResources().getColor(R.color.color_gray));

            itemList.clear();
            itemList.addAll(hasDoList);
            materielAdapter.notifyDataSetChanged();
        }

        fillMaterialView();
    }

    /**
     * 获取领料发货详细数据
     */
    private void getMaterierSendGoodDetail() {
        ApiService api = HttpMethod.getInstance().create(ApiService.class);
        api.getMaterierSendGoodsDetail(noticeOrderId)
                .compose(RxSchedulers.<BaseInfo<PickSendGoodsDetail>>compose(this))
                .subscribe(new BaseObserver<PickSendGoodsDetail>() {
                    @Override
                    public void onSuccess(BaseInfo<PickSendGoodsDetail> baseInfo) {
                        if (baseInfo != null && baseInfo.getData() != null) {
                            mDetail = baseInfo.getData();

                            //填充顶部
                            fillTopView();

                            //横向物料布局的填充
                            fillHorizontalRecyclerView();

                            fillMaterialView();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                    }
                });
    }

    /**
     * 填充订单布局信息
     */
    private void fillTopView() {
        //通知单订单号
        showNoticeLetterNo.setText(mDetail.getNoticeOrderNo());
        //通知单状态
        positionStatusName.setText(mDetail.getDisplayNodOrderStatusName());
        //业务类型
        showFirstValue.setText(mDetail.getBussTypeName());
        //供应商
        showSecondValue.setText(mDetail.getSaleDealerName());
        //车牌号
        showThirdValue.setText(mDetail.getCarNo());
        //司机
        showFourthValue.setText(mDetail.getDriverName());
    }

    /**
     * 填充横向 物料布局,注意这里要区分是，已作业还是未来作业的数据
     */
    private void fillHorizontalRecyclerView() {
        if (mDetail.getHasJobInfo() == null && mDetail.getNotJobInfo() == null)
            return;

        /*设置已作业和未作业，第一项为选中*/

        if (mDetail.getHasJobInfo() != null && mDetail.getHasJobInfo().size() > 0) {
            hasDoList.addAll(mDetail.getHasJobInfo());
            hasDoList.get(0).isSelected = true;

            //设定当前数据为已作业
            for (WorkInfoBean mpib : mDetail.getHasJobInfo()) {
                mpib.hasDo = true;
            }
        }

        if (mDetail.getNotJobInfo() != null && mDetail.getNotJobInfo().size() > 0) {
            unDoList.addAll(mDetail.getNotJobInfo());
            unDoList.get(0).isSelected = true;

            //设定当前数据为未作业
            for (WorkInfoBean mpib : mDetail.getNotJobInfo()) {
                mpib.hasDo = false;
            }
        }

        //注意初始情况下，是先显示未作业物料
        itemList.addAll(unDoList);
        materielAdapter.notifyDataSetChanged();
    }

    /**
     * 填充物料显示布局
     */
    private void fillMaterialView() {

        if (itemList.size() == 0) {
            showMaterielFirstValue.setText("");
            showMaterielSecondValue.setText("");
            showMaterielThirdValue.setText("");
            showMaterielFourthValue.setText("");
            materielFourthTv.setText(hasPositionShow ? "已作业数量:" : "未作业数据");

            currentShowMaterier = null;

            workDatas.clear();
            workAdapter.notifyDataSetChanged();

            return;
        }

        for (WorkInfoBean item : itemList) {
            if (item.isSelected) {
                currentShowMaterier = item;
                break;
            }
        }

        showMaterielFirstValue.setText(currentShowMaterier.skuCode);
        showMaterielSecondValue.setText(currentShowMaterier.skuName);
        showMaterielThirdValue.setText(currentShowMaterier.detailAmount + "件/" + currentShowMaterier.detailWeight + "吨");
        showMaterielFourthValue.setText(hasPositionShow ? currentShowMaterier.jobAmount + "件/" + currentShowMaterier.jobWeight + "吨" :
                currentShowMaterier.notJobAmount + "件/" + currentShowMaterier.notJobWeight + "吨");
        materielFourthTv.setText(hasPositionShow ? "已作业数量:" : "未作业数量:");

        workDatas.clear();
        workDatas.addAll(currentShowMaterier.hasDo ? currentShowMaterier.getJobInfoList() :
                currentShowMaterier.getPositionInfoList());
        workAdapter.notifyDataSetChanged();

        currentPostionItem = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (requestCode) {

            //选择库存
            case AppConfig.BaseDataAction.REQCODE_CHOOSE_STOCK:
                if (data.hasExtra("selectBean")) {
                    SearchStockBean selectBean = (SearchStockBean) data.getSerializableExtra("selectBean");
                    dealSelectStockResult(selectBean);
                }
                break;

            //添加作业记录
            case AppConfig.BaseDataAction.REQCODE_ADD_OPERATE_REMARK:
                ArrayList<WorkNotesBean> remarks = (ArrayList<WorkNotesBean>) data.getSerializableExtra("remarks");

                if (remarks != null) {
                    if (currentPostionItem instanceof PositionInfoBean) {
                        PositionInfoBean pf = (PositionInfoBean) currentPostionItem;
                        pf.setJobAmountList(remarks);
                    }
                    //
                    else {
                        JobInfoBean jb = (JobInfoBean) currentPostionItem;
                        jb.setJobAmountList(remarks);
                    }

                    workAdapter.notifyDataSetChanged();
                }

                break;


            case PictureConfig.CHOOSE_REQUEST:
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);

                if (selectList == null || selectList.size() == 0)
                    return;

                List<JobAttachBean> photos = new ArrayList<>();

                for (LocalMedia media : selectList) {
                    JobAttachBean jobAttachBean = new JobAttachBean();
                    jobAttachBean.photoPath = media.getPath();
                    photos.add(jobAttachBean);
                }

                if (currentPostionItem instanceof PositionInfoBean) {
                    PositionInfoBean pf = (PositionInfoBean) currentPostionItem;

                    pf.getJobAttachList().addAll(photos);
                    pf.setJobAttachList(pf.getJobAttachList());
                }
                //
                else {
                    JobInfoBean jb = (JobInfoBean) currentPostionItem;

                    jb.getJobAttachList().addAll(photos);
                    jb.setJobAttachList(jb.getJobAttachList());
                }

                workAdapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 处理选择库存
     *
     * @param selectBean
     */
    public void dealSelectStockResult(SearchStockBean selectBean) {
        /**在获取到数据过后，需要注意是 新整还是更改*/
        //如果是新整
        if (currentPostionItem == null) {

            if (!currentShowMaterier.hasDo) {
                PositionInfoBean pb = new PositionInfoBean();
                pb.stockId = selectBean.getStockId();
                pb.stockName = selectBean.getStockName();
                pb.whId = selectBean.getWhId();
                pb.whName = selectBean.getWhName();
                pb.invId = selectBean.getId();
                pb.stockStatusName = selectBean.getStockStatusName();
                pb.stockStatus = selectBean.getStockStatus();
                pb.stockType = selectBean.getStockType();
                pb.stockTypeName = selectBean.getStockTypeName();

                pb.availableInventoryPiece = new BigDecimal(selectBean.getAvailableInventoryPiece());
                pb.availableInventorySquare = new BigDecimal(selectBean.getAvailableInventorySquare());
                pb.availableInventoryTon = new BigDecimal(selectBean.getAvailableInventoryTon());
                pb.packageWeight = BigDecimalUtil.getBigDecimalByString(selectBean.getPackageWeight());

                pb.batchNo = selectBean.getBatchNo();
                pb.unitName = selectBean.getUnitName();
                pb.unitId = selectBean.getUnitId();

                pb.fromSelectStock = true;

                currentShowMaterier.getPositionInfoList().add(pb);
                workDatas.add(pb);
            }
            //
            else {
                JobInfoBean jb = new JobInfoBean();
                jb.actualStockId = selectBean.getStockId();
                jb.actualStockName = selectBean.getStockName();
                jb.actualWhId = selectBean.getWhId();
                jb.actualWhName = selectBean.getWhName();
                jb.invId = selectBean.getId();
                jb.stockStatusName = selectBean.getStockStatusName();
                jb.stockStatus = selectBean.getStockStatus();
                jb.stockType = selectBean.getStockType();
                jb.stockTypeName = selectBean.getStockTypeName();

                jb.fromSelectStock = true;

                jb.availableInventoryPiece = new BigDecimal(selectBean.getAvailableInventoryPiece());
                jb.availableInventorySquare = new BigDecimal(selectBean.getAvailableInventorySquare());
                jb.availableInventoryTon = new BigDecimal(selectBean.getAvailableInventoryTon());
                jb.packageWeight = BigDecimalUtil.getBigDecimalByString(selectBean.getPackageWeight());

                jb.batchNo = selectBean.getBatchNo();
                jb.unitName = selectBean.getUnitName();
                jb.unitId = selectBean.getUnitId();

                currentShowMaterier.getJobInfoList().add(jb);
                workDatas.add(jb);
            }

            workAdapter.notifyDataSetChanged();

            return;
        }

        /**下面是更改操作*/
        //未作业
        if (currentPostionItem instanceof PositionInfoBean) {

            PositionInfoBean rcItem = (PositionInfoBean) currentPostionItem;
            rcItem.stockId = selectBean.getStockId();
            rcItem.stockName = selectBean.getStockName();
            rcItem.whId = selectBean.getWhId();
            rcItem.whName = selectBean.getWhName();
            rcItem.invId = selectBean.getId();
            rcItem.stockStatusName = selectBean.getStockStatusName();
            rcItem.stockStatus = selectBean.getStockStatus();
            rcItem.stockType = selectBean.getStockType();
            rcItem.stockTypeName = selectBean.getStockTypeName();

            rcItem.availableInventoryPiece = new BigDecimal(selectBean.getAvailableInventoryPiece());
            rcItem.availableInventorySquare = new BigDecimal(selectBean.getAvailableInventorySquare());
            rcItem.availableInventoryTon = new BigDecimal(selectBean.getAvailableInventoryTon());
            rcItem.packageWeight = BigDecimalUtil.getBigDecimalByString(selectBean.getPackageWeight());

            rcItem.batchNo = selectBean.getBatchNo();
            rcItem.unitName = selectBean.getUnitName();
            rcItem.unitId = selectBean.getUnitId();

            rcItem.fromSelectStock = true;

            rcItem.isPostPositon = false;
        }
        //已作业
        else {
            JobInfoBean jb = (JobInfoBean) currentPostionItem;
            jb.actualStockId = selectBean.getStockId();
            jb.actualStockName = selectBean.getStockName();
            jb.actualWhId = selectBean.getWhId();
            jb.actualWhName = selectBean.getWhName();
            jb.invId = selectBean.getId();
            jb.stockStatusName = selectBean.getStockStatusName();
            jb.stockStatus = selectBean.getStockStatus();
            jb.stockType = selectBean.getStockType();
            jb.stockTypeName = selectBean.getStockTypeName();

            jb.availableInventoryPiece = new BigDecimal(selectBean.getAvailableInventoryPiece());
            jb.availableInventorySquare = new BigDecimal(selectBean.getAvailableInventorySquare());
            jb.availableInventoryTon = new BigDecimal(selectBean.getAvailableInventoryTon());
            jb.packageWeight = BigDecimalUtil.getBigDecimalByString(selectBean.getPackageWeight());

            jb.batchNo = selectBean.getBatchNo();
            jb.unitName = selectBean.getUnitName();
            jb.unitId = selectBean.getUnitId();

            jb.fromSelectStock = true;
            jb.isPostPositon = false;
        }

        workAdapter.notifyDataSetChanged();
    }

    /**
     * 确认提交作业
     */
    private void saveOperate() {
        MaterierSendGoodPost post = new MaterierSendGoodPost();

        //未作业
        if (!currentShowMaterier.hasDo) {
            PositionInfoBean rpib = (PositionInfoBean) currentPostionItem;

            post.id = StringUtils.isCanUse(rpib.id) ? rpib.id : "";
            post.orderId = mDetail.getOrderId();
            post.orderNo = mDetail.getOrderNo();
            post.orderDetailId = currentShowMaterier.orderDetailId;
            //作业类型	(1:出库)
            post.jobType = 1;
            post.isActual = StringUtils.isCanUse(mDetail.getNoticeOrderId()) ? 1 : 0;
            post.actualStockId = rpib.actualStockId;
            post.actualWhId = rpib.actualWhId;
            post.invId = rpib.invId;
            post.packageWeight = rpib.packageWeight;
            post.skuId = currentShowMaterier.skuId;
            post.skuCode = currentShowMaterier.skuCode;
            post.skuName = currentShowMaterier.skuName;
            post.actualAmount = rpib.amount;
            post.actualWeight = rpib.weight;
            post.actualVolume = rpib.volume;
            post.stockStatus = rpib.stockStatus;
            post.stockType = rpib.stockType;
            post.unitId = rpib.unitId;
            post.batchNo = rpib.batchNo;
            post.remark = rpib.remark;
            post.jobAmountList = rpib.getJobAmountList() == null ? new ArrayList<WorkNotesBean>() : rpib.getJobAmountList();
            post.jobAttachList = rpib.getJobAttachList();

            post.noticeOrderId = noticeOrderId;
            post.noticeOrderNo = noticeOrderNo;
            post.noticeOrderDetailId = currentShowMaterier.noticeOrderDetailId;


        }
        //已作业
        else {

            JobInfoBean jb = (JobInfoBean) currentPostionItem;


            post.id = StringUtils.isCanUse(jb.id) ? jb.id : "";
            post.orderId = mDetail.getOrderId();
            post.orderNo = mDetail.getOrderNo();
            post.orderDetailId = currentShowMaterier.orderDetailId;
            //作业类型	(1:出库)
            post.jobType = 1;
            post.isActual = StringUtils.isCanUse(mDetail.getNoticeOrderId()) ? 1 : 0;
            post.actualStockId = jb.actualStockId;
            post.actualWhId = jb.actualWhId;
            post.invId = jb.invId;
            post.packageWeight = jb.packageWeight;
            post.skuId = currentShowMaterier.skuId;
            post.skuCode = currentShowMaterier.skuCode;
            post.skuName = currentShowMaterier.skuName;
            post.actualAmount = jb.amount;
            post.actualWeight = jb.weight;
            post.actualVolume = jb.volume;

            post.stockStatus = jb.stockStatus;
            post.stockType = jb.stockType;
            post.unitId = jb.unitId;
            post.batchNo = jb.batchNo;
            post.remark = jb.remark;
            post.jobAmountList = jb.getJobAmountList() == null ? new ArrayList<WorkNotesBean>() : jb.getJobAmountList();
            post.jobAttachList = jb.getJobAttachList();

            post.noticeOrderId = noticeOrderId;
            post.noticeOrderNo = noticeOrderNo;
            post.noticeOrderDetailId = currentShowMaterier.noticeOrderDetailId;
        }

        ApiService api = HttpMethod.getInstance().create(ApiService.class);
        api.savaSendGoodsOperate(post)
                .compose(RxSchedulers.<BaseInfo<String>>compose(this))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(BaseInfo<String> baseInfo) {
                        if (baseInfo != null && baseInfo.getData() != null) {
                            Toast.makeText(PickDeliverGoodsActivity.this, "确认作业成功!"
                                    , Toast.LENGTH_SHORT).show();

                            //未作业情况下
                            if (currentPostionItem instanceof PositionInfoBean) {
                                PositionInfoBean temp = (PositionInfoBean) currentPostionItem;
                                temp.isPostPositon = true;
                            }
                            //
                            else {
                                JobInfoBean temp = (JobInfoBean) currentPostionItem;
                                temp.isPostPositon = true;
                            }

                            workAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(PickDeliverGoodsActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

